package com.yzh.openai.domain.openai.service.rule.impl;

import com.yzh.openai.domain.openai.annotation.LogicStrategy;
import com.yzh.openai.domain.openai.model.aggregates.ChatProcessAggregate;
import com.yzh.openai.domain.openai.model.entity.RuleLogicEntity;
import com.yzh.openai.domain.openai.model.entity.UserAccountEntity;
import com.yzh.openai.domain.openai.model.valobj.LogicCheckTypeVO;
import com.yzh.openai.domain.openai.repository.IOpenAiRepository;
import com.yzh.openai.domain.openai.service.rule.ILogicFilter;
import com.yzh.openai.domain.openai.service.rule.factory.DefaultLogicFactory;
import com.yzh.openai.types.enums.AIModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.ExecutionException;

/**
 * 用户额度扣减规则规律
 */
@Slf4j
@Component
@LogicStrategy(logicMode = DefaultLogicFactory.LogicModel.USER_QUOTA)
public class UserQuotaFilter implements ILogicFilter<UserAccountEntity> {
    @Resource
    private IOpenAiRepository openAiRepository;

    @Override
    public RuleLogicEntity<ChatProcessAggregate> filter(ChatProcessAggregate chatProcess, UserAccountEntity data) throws ExecutionException {
        if (data.getSurplusQuota() > 0) {
            //扣减账户额度，个人账户无资源竞争，后续可以优化Redis
            //获取当前使用模型的售价（消费次数）
            int cost = AIModel.getEnum(chatProcess.getModel().getCode()).getCost();
            int result = openAiRepository.subAccountQuota(chatProcess.getOpenid(), cost);
            if (result != 0) {
                return RuleLogicEntity.<ChatProcessAggregate>builder()
                        .type(LogicCheckTypeVO.SUCCESS)
                        .data(chatProcess)
                        .build();
            }
        }
        return RuleLogicEntity.<ChatProcessAggregate>builder()
                .type(LogicCheckTypeVO.REFUSE)
                .info("账户额度【" + data.getTotalQuota() + "】次已耗尽！请充值使用☺️")
                .build();
    }
}
